﻿using System;
using System.Collections.Generic;
using iTextSharp.text;
using iTextSharp.text.pdf;
using System.Text;
using Ch.Admin.Bfs.Sms.Sdmx.Extension.CodeBook.Meta;
using Ch.Admin.Bfs.Sms.Sdmx.Extension.CodeBook.Configuration;

namespace Ch.Admin.Bfs.Sms.Sdmx.Extension.CodeBook.Pdf
{
    public class CatVarModule : BaseModule
    {
        public CatVarModule(IMetaProvider provider, Document pdfDocument, PdfFonts fontsProvider, BookConfiguration cfg)
            : base(provider, pdfDocument, fontsProvider, cfg)
        {
            // Maintenable artefact ID, name, Descr and Annotations
            HierarchyNode rootNode = metaProvider.GetRootNode();
            // FullId of related quest ?
            questFullId = rootNode.refArt;

            PropertyTable pt = new PropertyTable(provider, fontsProvider, pdfDocument);
            pt.AddMainTitle(rootNode.Name);
            pt.AddLeading(5f);
                pt.AddProperty("Description", rootNode.Descr);
            pt.AddLeading(12f);

            pt.AddAnnotations( metaProvider.GetAnnotations(rootNode));
            Tables.Add(new PdfBookPTable(pt.Table, true));

            // Aperçu hierarchique des variables
            CatalogHierarchy cat = new CatalogHierarchy(provider, true, false, fontsProvider, pdfDocument);
            Tables.Add(new PdfBookPTable(cat.Table));
            cat.FillTable(rootNode);

            // Detail des variables
            pt = new PropertyTable(metaProvider, BookFonts, doc);
            Tables.Add(new PdfBookPTable(pt.Table, true));
            pt.AddMainTitle(BookConfig.TitleVarDetail[BookConfig.LanguageId]);
            TableParagraph();

            int index = 0;
            foreach (HierarchyNode childNode in rootNode.Nodes)
                AddDetailRecurse(null, childNode, string.Empty, 0, ++index);


        }

        private void AddDetailRecurse(HierarchyNode parentNode, HierarchyNode node, string parentlevelId, int level, int index)
        {
            try
            {
                string parentInfo = parentNode == null ? string.Empty : parentNode.Id + ": " + parentNode.Name;
                PropertyTable pt = new PropertyTable(metaProvider, BookFonts, doc);
                pt.QuestFullId = questFullId;
                Tables.Add(new PdfBookPTable(pt.Table));
                TableParagraph();

                string levelId = string.IsNullOrEmpty(parentlevelId) ? index.ToString() : parentlevelId + "." + index.ToString();
                string text = string.Format("{0} {1}", levelId, node.Id);
                string target = metaProvider.FullIdKey + node.Id;
                pt.AddAnchoredTitle(text, node.Name, target);

                // Description (if any)
                pt.AddProperty("Description", node.Descr);

                // ParentInfo
                pt.AddProperty("Parent", parentInfo);

                // Textype and detail
                List<KeyValuePair<string, string>> typeDetailList = metaProvider.GetTypeDetail(node);
                for (int i = 0; i < typeDetailList.Count; i++)
                {
                    pt.AddProperty(typeDetailList[i].Key, typeDetailList[i].Value);
                }

                // Codelist
                HierarchyNode codelistNode = metaProvider.GetCodelistReference(node);
                if (codelistNode != null)
                {
                    // Id contains the full id
                    string[] idElem = codelistNode.Id.Split('+');
                    string reference = idElem[1] + " (" + idElem[0] + ") " + Environment.NewLine;

                    pt.AddAnchorProperty("Codelist", codelistNode.Name + Environment.NewLine + " (" + codelistNode.Id + ")", "#" + codelistNode.Id, false);
                }

                // Quality associated
                if (CatalogHierarchy.HasSubConceptFlag(node))
                {
                    codelistNode = metaProvider.GetCodelistReference(node.Nodes[0]);
                    if (codelistNode != null)
                    {
                        string[] idElem = codelistNode.Id.Split('+');
                        string reference = idElem[1] + " (" + idElem[0] + ") " + Environment.NewLine;

                        pt.AddAnchorProperty("Quality Codes", codelistNode.Name + Environment.NewLine + " (" + codelistNode.Id + ")", "#" + codelistNode.Id, false);
                    }
                }
                if (node.Id == "EL08")
                {
                    pt.AddAnnotations(metaProvider.GetAnnotations(node));
                }
                pt.AddAnnotations(metaProvider.GetAnnotations(node));

                int subIndex = 0;
                // Recurse but Skip flag quality var
                if (CatalogHierarchy.HasSubConceptFlag(node) == false)
                    foreach (HierarchyNode childNode in node.Nodes)
                        AddDetailRecurse(node, childNode, levelId, level + 1, ++subIndex);
            }
            catch (Exception ex)
            {
                throw (ex);
            }

        }


        private void ValLevelList(HierarchyNode node, int level, int index, string parentParagraph)
        {
            string paragraph = string.Empty;
            PdfPTable table = null;

            #region Node Detail

            // node detail
            if (level == 1)
            {
            }
            else
            {
                paragraph = parentParagraph + index.ToString() + ".";
                table = MakeTableVarDetail(node, index, paragraph);
            }
            // Add current node detail table
            Tables.Add(new PdfBookPTable(table));

            // Any annotations
            CreateAnnotationTable(metaProvider.GetAnnotations(node));


            #endregion

            #region Node sub items

            // List child nodes as table
            if (node.Nodes.Count > 0)
            {
                table = new PdfPTable(3);
                float[] widths = new float[] { 10f, 79f, 11f };
                table.SetWidths(widths);
                table.TotalWidth = TotalWidth;
                Tables.Add(new PdfBookPTable(table));

                // Title for sub table list
                if (level > 1)
                {
                    Phrase ph = new Phrase("Tableau des sous éléments", BookFonts.FontLevelTwo);
                    PdfPCell cell = new PdfPCell(ph);
                    cell.Border = Rectangle.NO_BORDER;
                    cell.Colspan = table.NumberOfColumns;
                    table.AddCell(cell);
                }

                // Table title
                table.AddCell(MakeTitleCell("No"));
                table.AddCell(MakeTitleCell("ID: Name"));
                table.AddCell(MakeTitleCell("Type"));

                
                // Iterates items
                int no = 1;
                foreach (HierarchyNode childNode in node.Nodes)
                {
                    // create row of list
                    bool isAlternatedColor = no % 2 == 0 ? true : false;
                    table.AddCell(MakeTableCell(no.ToString(), isAlternatedColor));
                    table.AddCell(MakeTableCell(string.Format("{0}: {1}", childNode.Id, childNode.Name), 
                        isAlternatedColor, "#" + metaProvider.FullIdKey + childNode.Id, 2));
                    // Type of variable
                    table.AddCell(MakeTableCell(metaProvider.GetVariableType(childNode), isAlternatedColor));

                    // Create lower level Table list
                    ValLevelList(childNode, level + 1, no, paragraph);
                    ++no;
                }
            }
            #endregion

        }

        private PdfPTable MakeTableVarDetail(HierarchyNode node, int index, string paragraph)
        {
            PdfPTable table = CreatePropertyTable();

            // Var ID - Title
            Phrase ph = new Phrase(paragraph + " " + node.Id + " :  " + node.Name, BookFonts.FontProperty);
            Anchor target = new Anchor(ph);
            target.Name = metaProvider.FullIdKey + node.Id;
            PdfPCell cell = new PdfPCell(target);
            cell.Border = Rectangle.NO_BORDER;
            cell.Colspan = 2;
            //cell.BackgroundColor = new BaseColor(BookFonts.COLOR_TABLE_HEAD);

           // cell.PaddingTop = 8f;
            table.AddCell(cell);

            // Description (if any)
            string descr = node.Descr;
            if (string.IsNullOrEmpty(descr) == false)
                MakeRowVarDetail(table, "Description", descr, false);

            // Textype and detail
            List<KeyValuePair<string, string>> typeDetailList = metaProvider.GetTypeDetail(node);
            for (int i = 0; i < typeDetailList.Count; i++)
            {
                MakeRowVarDetail(table, typeDetailList[i].Key, typeDetailList[i].Value, i > 0);
            }

            // Codelist
            HierarchyNode codelistNode = metaProvider.GetCodelistReference(node);
            if (codelistNode != null)
            {
                // Id contains the full id
                string[] idElem = codelistNode.Id.Split('+');
                string reference = idElem[1] + " (" + idElem[0] + ") " + Environment.NewLine;

                MakeRowVarDetail(table, "Codelist", reference, "#"+codelistNode.Id ,false);
                MakeRowVarDetail(table, "Name", codelistNode.Name, true);
            }


            return table;
        }

    }

}
